<!--
 * @Description:总收入对账
-->
<template>
  <div class="registered-container totalRevenue appMainWarp">
    <el-form :inline="true" :model="searchKey" class="demo-form-inline">
      <el-form-item>
        <el-button :type="0 == quaflat ? 'primary':''" @click="getlisttable(0)">按天显示</el-button>
        <el-button :type="1 == quaflat ? 'primary':''" @click="getlisttable(1)">按月显示</el-button>
        <el-button :type="2 == quaflat ? 'primary':''" @click="getlisttable(2)">按年显示</el-button>
        <el-button :type="3 == quaflat ? 'primary':''" @click="getlisttable(3)">汇总显示</el-button>
      </el-form-item>
      <el-form-item label="页面展示方式:">
        <el-select v-model="searchKey.paytype" placeholder="请选择" @change="onSearch">
          <el-option
            v-for="item in searchKey.paytypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易时间:">
        <el-date-picker
          v-model="searchKey.time"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          :clearable="false"
        />
      </el-form-item>

      <el-form-item label="院区:">
        <el-select v-model="searchKey.hospital_area_no" placeholder="请选择">
          <el-option
            v-for="item in searchKey.Hospital"
            :key="item.area_code"
            :label="item.area_name"
            :value="item.area_code"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="选择支付场景:">
        <el-select v-model="searchKey.system_no" multiple placeholder="请选择支付场景" clearable>
          <el-option
            v-for="item in searchKey.System"
            :key="item.pay_scene_no"
            :label="item.pay_scene_name"
            :value="item.pay_scene_no"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="对账业务:">
        <el-select v-model="searchKey.reconciliation" placeholder="请选择" @change="onLoad">
          <el-option
            v-for="item in searchKey.reconciliationList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onLoad">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-download" @click="onExport">导出</el-button>
      </el-form-item>
    </el-form>

    <template>
      <el-table
        v-if="searchKey.paytype==='Z'"
        ref="table"
        v-loading="page.tableLoading"
        v-el-height-adaptive-table="{bottomOffset: 90}"
        max-height="500px"
        center
        class="table"
        :data="searchData"
        :span-method="objectSpanMethod"
        stripe
        border
      >
        <el-table-column label="时间" align="center">
          <template slot-scope="scope">{{ scope.row.date||'-' }}</template>
        </el-table-column>
        <el-table-column
          prop="pay_name"
          label="支付方式"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.pay_name||'-' }}</template>
        </el-table-column>
        <el-table-column
          prop="merchant"
          label="商户号"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.merchant||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation !== '3'"
          :key="1"
          prop="self_total_fee"
          label="支付场景收入"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.self_total_fee||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation !== '2'"
          :key="2"
          prop="his_total_fee"
          label="HIS系统收入"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.his_total_fee	||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation !== '1'"
          :key="3"
          prop="bank_total_fee"
          label="支付系统收入"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.bank_total_fee	||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation == '1' || searchKey.reconciliation == '4'"
          :key="4"
          label="支付场景—HIS系统"
          align="center"
          prop="self_his"
        >
          <template slot-scope="scope">
            <div
              :class="[scope.row.self_his > 0|| scope.row.self_his < 0? 'abnormal':'normal']"
              @click="jumpClick(scope.row,1,scope.row.self_his)"
            >{{ scope.row.self_his ||'-' }}</div>
          </template>
        </el-table-column>

        <el-table-column
          v-if="searchKey.reconciliation == '2' || searchKey.reconciliation == '4'"
          :key="5"
          label="支付场景—支付系统"
          align="center"
          prop="self_bank"
        >
          <template slot-scope="scope">
            <div
              :class="[scope.row.self_bank >0 || scope.row.self_bank <0?'abnormal':'normal']"
              @click="jumpClick(scope.row,2,scope.row.self_bank)"
            >{{ scope.row.self_bank ||'-' }}</div>
          </template>
        </el-table-column>

        <el-table-column
          v-if="searchKey.reconciliation == '3' || searchKey.reconciliation == '4'"
          :key="6"
          label="HIS系统—支付系统"
          align="center"
          prop="his_bank"
        >
          <template slot-scope="scope">
            <div
              :class="[scope.row.his_bank>0 || scope.row.his_bank<0?'abnormal':'normal']"
              @click="jumpClick(scope.row,3,scope.row.his_bank)"
            >{{ scope.row.his_bank||'-' }}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-if="searchKey.paytype==='H'"
        ref="table"
        v-loading="page.tableLoading"
        v-el-height-adaptive-table="{bottomOffset: 90}"
        max-height="500px"
        center
        class="table"
        :data="searchData"
        :span-method="objectSpanMethod"
        stripe
        border
      >
        <el-table-column label="时间" align="center">
          <template slot-scope="scope">{{ scope.row.date||'-' }}</template>
        </el-table-column>
        <!-- <el-table-column
          prop="pay_name"
          label="支付方式"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.pay_name||'-' }}</template>
        </el-table-column> -->
        <el-table-column
          prop="scene_name"
          label="支付场景"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.scene_name||'-' }}</template>
        </el-table-column>
        <el-table-column
          prop="wx_total"
          label="微信金额"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.wx_total||'-' }}</template>
        </el-table-column>
        <el-table-column
          prop="ali_total"
          label="支付宝金额"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.ali_total||'-' }}</template>
        </el-table-column>
        <el-table-column
          prop="bank_total"
          label="银行卡金额"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.bank_total||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation !== '3'"
          :key="1"
          prop="self_total_fee"
          label="支付场景金额"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.self_total_fee||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation !== '2'"
          :key="2"
          prop="his_total_fee"
          label="HIS系统收入"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.his_total_fee	||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation !== '1'"
          :key="3"
          prop="bank_total_fee"
          label="支付系统收入"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.bank_total_fee	||'-' }}</template>
        </el-table-column>
        <el-table-column
          v-if="searchKey.reconciliation == '1' || searchKey.reconciliation == '4'"
          :key="4"
          label="支付场景—HIS系统"
          align="center"
          prop="self_his"
        >
          <template slot-scope="scope">
            <div
              :class="[scope.row.self_his > 0|| scope.row.self_his < 0? 'abnormal':'normal']"
              @click="jumpClick(scope.row,1,scope.row.self_his)"
            >{{ scope.row.self_his ||'-' }}</div>
          </template>
        </el-table-column>

        <el-table-column
          v-if="searchKey.reconciliation == '2' || searchKey.reconciliation == '4'"
          :key="5"
          label="支付场景—支付系统"
          align="center"
          prop="self_bank"
        >
          <template slot-scope="scope">
            <div
              :class="[scope.row.self_bank >0 || scope.row.self_bank <0?'abnormal':'normal']"
              @click="jumpClick(scope.row,2,scope.row.self_bank)"
            >{{ scope.row.self_bank ||'-' }}</div>
          </template>
        </el-table-column>

        <el-table-column
          v-if="searchKey.reconciliation == '3' || searchKey.reconciliation == '4'"
          :key="6"
          label="HIS系统—支付系统"
          align="center"
          prop="his_bank"
        >
          <template slot-scope="scope">
            <div
              :class="[scope.row.his_bank>0 || scope.row.his_bank<0?'abnormal':'normal']"
              @click="jumpClick(scope.row,3,scope.row.his_bank)"
            >{{ scope.row.his_bank||'-' }}</div>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <pagination
      :total="page.totalRow"
      :page.sync="page.currentPage"
      :limit.sync="page.pageSize"
      @pagination="onSearch"
    />
  </div>
</template>

<script>
import elHeightAdaptiveTable from '@/directive/el-table'
import { getConfigType } from '@/api/transactRecords/index'
import { payType } from '@/api/generaLedger/index'
import Pagination from '@/components/Pagination' // 分页
import { getCompareType } from '@/utils/auth'
export default {
  name: 'Payment',
  components: {
    Pagination
  },
  directives: { elHeightAdaptiveTable },

  data() {
    return {
      quaflat: 0, // 按钮默认
      date: 'day', // 按天月年
      searchKey: {
        paytype: 'Z',
        time: '', // 交易日期
        hospital_area_no: '', // 选择院区
        Hospital: [],
        system_no: '', // 平台
        System: [],
        reconciliation: '1', // 对账业务
        reconciliationList: [],
        paytypeList: [{ id: 'H', name: '横向' }, { id: 'Z', name: '纵向' }]
      },

      searchData: [],
      date_type: '', // 按什么显示
      self_his: '1,2',
      self_bank: '1,3',
      his_bank: '2,3',

      page: {
        tableLoading: false,
        currentPage: 1, // 当前页
        pageSize: 20, // 默认条数
        totalRow: 0, // 总条数
        totalPage: 0 // 总页数
      },
      minDate: '',
      maxDate: '',
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.minDate = minDate
          this.maxDate = maxDate
        },
        disabledDate: (time) => { // 查询时间跨度为365天
          if (this.minDate) {
            var range = 365 * 24 * 3600 * 1000
            return time.getTime() > Date.now() || time.getTime() > (this.minDate.getTime() + range) || time.getTime() < (this.minDate.getTime() - range)
          }
          return time.getTime() > Date.now()
        }
      },
      position: 0, // 合并单元格
      rowSpanArr: [], // 合并单元格
      compare: '', // 对账业务
      system: '' // 平台
    }
  },
  watch: {
    'searchKey.time': {
      deep: true,
      handler(val) {
        if (val == null) {
          this.minDate = null
        }
      }
    }
  },
  created() {
    this.searchKey.time = this.utils.Formonth()
    this.searchKey.reconciliation = getCompareType()
  },
  mounted() {
    this.getConfig()
    this.onLoad()
  },
  methods: {
    // 表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return this.ret(row, 'firstSpan')
      } else if (columnIndex === 1) {
        return this.ret(row, 'secondSpan')
      }
    },
    ret(row, obj) {
      if (row && row[obj] !== 0) {
        return {
          rowspan: row[obj],
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    // 计算第一列合并总数
    computeFirstSpan(firstObj, secondObj) {
      // 遍历计算第一列合并行数
      for (var obj in firstObj) {
        var fristData = this.searchData.filter(d => d.idx === firstObj[obj][0])[0]
        // 获取第一条数据，对其添加 'firstSpan' 属性，并设置值
        if (fristData) fristData['firstSpan'] = firstObj[obj].length
        this.computeSecondSpan(firstObj[obj], secondObj)
      }
    },
    // 计算第二列合并总数
    computeSecondSpan(classList, secondObj) {
      var secondList = []
      // 遍历计算第二列合并行数
      for (var obj in secondObj) {
        // 判断两个id数组，取其并集，并集的长度就是合并列的行数
        var secondIds = secondObj[obj].filter(val => {
          return classList.indexOf(val) > -1
        })
        var fristData = this.searchData.filter(d => d.idx === secondIds[0])[0]
        // 获取第一条数据，对其添加 'secondSpan' 属性，并设置值
        if (fristData) fristData['secondSpan'] = secondIds.length
        secondList.push(secondIds)
      }
    },
    buildMerge(searchData) {
      var firstObj = {}
      var secondObj = {}
      var firstObjKey = ''
      var secondObjKey = ''
      // 本示例合并的前四列，对应的字段分别：date、pay_name
      // 如果你需要合并其他的字段，需修改此处字段名称
      for (var i = 0, len = searchData.length; i < len; i++) {
        firstObjKey = searchData[i].date
        secondObjKey = searchData[i].pay_name
        if (!firstObj[firstObjKey]) {
          firstObj[firstObjKey] = new Array(searchData[i].idx)
        } else {
          firstObj[firstObjKey].push(searchData[i].idx)
        }
        if (!secondObj[secondObjKey]) {
          secondObj[secondObjKey] = new Array(searchData[i].idx)
        } else {
          secondObj[secondObjKey].push(searchData[i].idx)
        }
      }
      this.computeFirstSpan(firstObj, secondObj)
    },
    // 系统配置搜索
    getConfig() {
      var that = this
      var params = {}
      getConfigType(params)
        .then(res => {
          that.searchKey.Hospital = res.data.hospital
          that.searchKey.System = res.data.scene
          that.searchKey.reconciliationList = res.data.compare
        })
        .catch(() => {})
    },
    // 查询列表
    onLoad() {
      this.page.currentPage = 1
      this.onSearch()
    },
    onSearch() {
      var params = {}
      var that = this
      params.page = that.page.currentPage // 当前页数
      params.limit = that.page.pageSize // 每页展示条数
      params.daytype = that.date
      if (that.searchKey.time && that.searchKey.time.length > 0) {
        params.startime = that.searchKey.time[0]
        params.endtime = that.searchKey.time[1]
      } else {
        params.startime = ''
        params.endtime = ''
      }
      params.hospital = that.searchKey.hospital_area_no
      params.sceneno = that.searchKey.system_no.toString()
      params.paytype = that.searchKey.paytype
      params.bustype = that.searchKey.reconciliation
      that.page.tableLoading = true
      payType(params)
        .then((res) => {
          that.page.tableLoading = false
          that.searchData = res.data.result
          if (this.searchData.length > 0) {
            this.searchData.forEach((data, index) => {
              if (!data.idx) {
                data['idx'] = String(index + 1)
              }
            })
            this.buildMerge(this.searchData)
          }
          that.page.totalPage = res.data.pages
          that.page.totalRow = parseInt(res.data.count)
        })
        .catch(() => {
          that.page.tableLoading = true
        })
    },
    // 导出
    onExport() {
      var params = {}
      var that = this
      params.page = that.page.currentPage // 当前页数
      params.limit = that.page.pageSize // 每页展示条数
      params.daytype = that.date
      if (that.searchKey.time && that.searchKey.time.length > 0) {
        params.startime = that.searchKey.time[0]
        params.endtime = that.searchKey.time[1]
      } else {
        params.startime = ''
        params.endtime = ''
      }
      params.hospital = that.searchKey.hospital_area_no
      params.sceneno = that.searchKey.system_no.toString()
      params.paytype = that.searchKey.paytype
      params.bustype = that.searchKey.reconciliation
      var viewUrl = `/cms/payCompare?&page=${params.page}&limit=${params.limit}&daytype=${
        params.daytype
      }&hospital=${
        params.hospital
      }&startime=${
        params.startime
      }&endtime=${params.endtime}&sceneno=${params.sceneno}&bustype=${params.bustype}&paytype=${params.paytype}&export=${1}`
      window.location.href = process.env.VUE_APP_BASE_API + viewUrl
    },
    jumpClick(item, type, val) {
      // if (val === 0 || val === '0.00') {
      //   return
      // } else {
      this.$router.push({
        path: '/generaLedger/totalRevenue/totalRevenueDetail/index',
        query: {
          paystyle: item.pay_style,
          currentime: item.date,
          startime: this.searchKey.time[0],
          endtime: this.searchKey.time[1],
          comparetype: type
        }
      })
      // }
    },
    getlisttable(flat) {
      this.quaflat = flat
      if (this.quaflat === 0) {
        this.date = 'day'
        this.onLoad()
      } else if (this.quaflat === 1) {
        this.date = 'month'
        this.onLoad()
      } else if (this.quaflat === 2) {
        this.date = 'year'
        this.onLoad()
      } else {
        this.date = 'all'
        this.onLoad()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.totalRevenue {
  position: relative;
  width: 100%;
  .demo-form-inline {
    .el-button--primary {
      background-color: #579ef8 !important;
      color: #fff !important;
    }
    .el-button {
      background-color: #e8f4ff;
      color: #579ef8;
      border: 1px solid rgba(87, 158, 248, 1);
    }
  }
  .abnormal {
    color: red;
    text-decoration: underline;
    cursor: pointer;
  }
  .normal {
    color: rgb(113, 118, 133);
    cursor: pointer;
  }
}
</style>

